<?php
namespace App\GraphQL\Mutations\MarketingPolicy;

use App\Models\MarketingPolicyRule;
use GraphQL\Type\Definition\ResolveInfo;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;

class CreateRule
{

    /**
     * Return a value for the field.
     *
     * @param null $rootValue
     *            Usually contains the result returned from the parent field. In this case, it is always `null`.
     * @param mixed[] $args
     *            The arguments that were passed into the field.
     * @param \Nuwave\Lighthouse\Support\Contracts\GraphQLContext $context
     *            Arbitrary data that is shared between all fields of a single query.
     * @param \GraphQL\Type\Definition\ResolveInfo $resolveInfo
     *            Information about the query itself, such as the execution state, the field name, path to the field from the root, and more.
     * @return mixed
     */
    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        $data = $args['input'];
        $authUser = auth()->user();
        $data['user_id']=$authUser->id;
        $this->validate($data);
        if($data['cate'] === 'ALLOWANCE') {
            $data['preference'] = intval($data['preference']*1000);
        }else{
            $data['preference'] = intval($data['preference']*100);
        }
        $rule = new MarketingPolicyRule($data);
        $rule->save();
        return $rule;
    }

    public function validate($data)
    {
        $cates = [
            'DERATE',
            'ALLOWANCE'
        ];
        $rules = [
            'name' => [
                'required',
                'max:18'
            ],
            'cate' => [
                'required',
                Rule::in($cates)
            ],
            'preference'=>[
                'required',
                'numeric'
            ],
        ];
        $messages = [
            'name.required' => '名称不能为空',
            'name.max' => '名称不能超过18个字',
            'cate.required' => '类型不能为空',
            'cate.in' => '类型不能超出限制',
            'preference.required' => '幅度不能为空',
            'preference.numeric' => '幅度为数字',
        ];
        $validate = Validator::make($data, $rules, $messages);
        if ($validate->fails()) {
            throw new \InvalidArgumentException($validate->messages()->first());
        }
        return true;
    }
}
